<template>
  <div class="index">
    <NavBar />
    <div class="dashboardAuth">
      <div class="head">
        <div class="container">
          <a href="javascript: void(0)" @click="$router.go(-1)" class='logo'><img src="../../assets/res/img/LOGO.png"></a>
          <span class="fr">
            <a href="javascript: void(0)" v-if="selectTable.status !== 2&&!loading" class="back" @click="submit('3')">保存草稿</a>
            <a href="javascript: void(0)" v-if="selectTable.status !== 2&&!loading" class="back on" @click="submit('2')">提交审稿</a>
            <a href="javascript: void(0)" v-if="selectTable.status === 2" class="back on" @click="$router.go(-1)">返回</a>
            <a @click="$router.go(-1)" href="javascript: void(0)" class="photo"><img :src="me.sysUser.avatar"></a>
          </span>
        </div>
      </div>
      <div class="container">
        <form class="layui-form con item" lay-filter="go">
          <div class="layui-form-item">
            <label class="layui-form-label"><i class="must">*</i>标题</label>
            <div class="layui-input-block">
              <input type="text" v-model="selectTable.title" name="title" placeholder="建议长度不超过30" lay-verify="required">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label"><i class="must">*</i>文章分类</label>
            <div class="layui-input-block">
              <div class="layui-inline" style="width:50%;">
                <select v-model="selectTable.classifyId" name="classifyId" lay-verify="required">
                  <option value="">请选择</option>
                  <option v-for="(item,index) in classifyList" :key="index" :value="item.classifyId">{{item.classifyName}}</option>
                </select>
              </div>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label"><i class="must">*</i>是否推荐</label>
            <div class="layui-input-block">
              <div class="layui-inline" style="width:20%;">
                <select name="locationLevel" v-model="selectTable.locationLevel">
                  <option value="">请选择</option>
                  <option value="0">是</option>
                  <option value="1">否</option>
                </select>
              </div>

              <span class="rec-tips">（说明：当天创建的文章最多仅能推荐一次）</span>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label"><i class="must">*</i>摘要</label>
            <div class="layui-input-block">
              <textarea v-model="selectTable.summary" name="summary" lay-verify="required" placeholder="建议长度不超过200" class="layui-textarea"></textarea>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label"><i class="must">*</i>标签</label>
            <div class="layui-input-block">
              <input type="text" v-model="selectTable.tag" name="title" placeholder="用半角逗号,分隔" lay-verify="required">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label"><i class="must">*</i>正文</label>
            <div class="layui-input-block">
              <textarea id="edit" style="display: none;" v-model="selectTable.details"></textarea>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">封面图片</label>
            <div class="layui-input-block">
              <div class="layui-inline" v-if="selectTable.imgUrl">
                <img :src="selectTable.imgUrl" style="width:182px;height:122px;">
              </div>
              <div class="layui-inline">
                <span class="pic layui-upload-drag" id="up_img">
                  <i class="layui-icon"></i>
                  <p>点击上传</p>
                </span>
                <span class="tips">尺寸180*120px<br>支持JPG、PNG、GIF图片，1M以内</span>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
    <Footer />
  </div>
</template>
<script>
import NavBar from '@/components/nav-bar'
import Footer from '@/components/footer'
import * as api from '@/service/api'
import { mapState } from 'vuex'
import cookie from '@/utils/cookie'
let $ = window.$
export default {
  components: {
    NavBar,
    Footer
  },
  data () {
    return {
      id: null,
      selectTable: {
        tag: '',
        imgUrl: null
      },
      classifyList: [],
      loading: false,
      layeditIndex: null
    }
  },
  computed: {
    ...mapState({
      me: state => state.me
    })
  },
  created () {
    this.getClassifyList()
  },
  watch: {
    id () {
      this.getData()
    }
  },
  mounted () {
    this.id = this.$route.params.id
    window.layui.use(['form', 'layedit', 'upload'], () => {
      var form = window.layui.form
      form.on('select', (data) => {
        this.$set(this.selectTable, $(data.elem).attr('name'), data.value)
      })
      let upload = window.layui.upload
      upload.render({
        elem: '#up_img',
        url: api.uploadUrl,
        headers: {
          accessToken: cookie.get('device_id')
        },
        before: (obj) => {
        },
        done: (res) => {
          this.selectTable.imgUrl = res.data.src
        }
      })
      var layedit = window.layui.layedit
      this.layeditIndex = layedit.build('edit', {
        uploadImage: {
          url: `${api.uploadUrl}&accessToken=${cookie.get('device_id')}`
        }
      })
    })
  },
  methods: {
    submit (status) {
      window.layui.use(['layer', 'layedit'], () => {
        this.selectTable.details = window.layui.layedit.getContent(this.layeditIndex)
        let layer = window.layui.layer
        this.selectTable.status = status
        if (!(this.selectTable.title && /^.{1,50}$/.test(this.selectTable.title))) {
          layer.msg('请输入1-50位字符的标题')
          return false
        }
        if (!(this.selectTable.classifyId)) {
          layer.msg('请选择分类')
          return false
        }
        if (!(this.selectTable.locationLevel)) {
          layer.msg('请选择是否推荐')
          return false
        }
        if (!(this.selectTable.tag && /^.{1,100}$/m.test(this.selectTable.tag))) {
          layer.msg('请输入1-100位字符的标签')
          return false
        }
        if (!(this.selectTable.summary && /^.{1,200}$/m.test(this.selectTable.summary))) {
          layer.msg('请输入1-200位字符的摘要')
          return false
        }
        if (!(this.selectTable.details && /^.{1,50000}$/m.test(this.selectTable.details))) {
          layer.msg('正文为空或者超长')
          return false
        }
        this.add()
      })
    },
    async add () {
      let layer = window.layui.layer
      if (this.selectTable.tag) {
        this.selectTable.tags = this.selectTable.tag.split(',')
      } else {
        this.selectTable.tags = []
      }
      try {
        if (this.id) {
          await api.getViewPointModify(this.selectTable)
        } else {
          await api.getViewPointAdd(this.selectTable)
        }
        this.$store.dispatch('getUserInfo')
        this.selectTable = {
          tag: '',
          imgUrl: null
        }
        layer.msg('提交成功')
        this.$router.push('/dashboardAuth')
      } catch (error) {
        layer.msg('出错了，提交失败')
      }
    },
    async getClassifyList () {
      let res = await api.getClassifyList({})
      this.classifyList = res.data.data
      // this.classifyList = [{classifyId: 1, classifyName: '哈哈'}]
      this.$nextTick(() => {
        window.layui.form && window.layui.form.render()
      })
    },
    async getData () {
      if (!this.id) {
        return false
      }
      this.loading = true
      let res = await api.getViewPointByid({ viewPointId: this.id })
      this.selectTable = res.data.data
      this.selectTable.locationLevel = this.selectTable.locationLevel.toString()
      this.selectTable.tag = this.selectTable.tags.join(',')
      this.loading = false
      this.$nextTick(() => {
        window.layui.form && window.layui.form.render()
        window.layui.use(['layedit'], () => {
          var layedit = window.layui.layedit
          this.layeditIndex = layedit.build('edit', {
            uploadImage: {
              url: `${api.uploadUrl}&accessToken=${cookie.get('device_id')}`
            }
          })
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../style/res/viewpoint";
.layui-input-block {
  margin-left: 135px;
}
.must {
  color: red;
  padding-right: 5px;
}
</style>
